In some countries of former Soviet Union there was a belief about lucky tickets. A >transport ticket of any sort was believed to posess luck if sum of digits on the left >half of its number was equal to the sum of digits on the right half. Here are examples >of such numbers:
003111 # 3 = 1 + 1 + 1
813372 # 8 + 1 + 3 = 3 + 7 + 2
17935 # 1 + 7 = 3 + 5 // if the length is odd, you should ignore the >middle number when adding the halves.
56328116 # 5 + 6 + 3 + 2 = 8 + 1 + 1 + 6
Such tickets were either eaten after being used or collected for bragging rights.Your task is to write a funtion luck_check(str), which returns true/True if argument is >string decimal representation of a lucky ticket number, or false/False for all other >numbers. It should throw errors for empty strings or strings which don't represent a >decimal number.
題目理解:設計一函式代入一皆為數字的字串string,若該字串左右半邊數字和相等則返還True,不等則返還False。其中若字串長度為奇數,則正中間的該數字皆不計入左右半邊和內。
def luck_check(string):
"""判斷字串左右半邊數字和是否相等"""
#將string以個別數字形式轉換成list
num_string = [int(i) for i in string]
#使用int()會自動無條件捨去
middle_index = int(len(string)/2)
#若字串個數為奇數,則不計中間數
if len(string)%2 == 1:
#對前半段與後半段數字的總和做比較,留意後半段索引+1以此來不計入中間數字
if sum(num_string[:middle_index]) == sum(num_string[middle_index+1:]):
return True
else:
#若為偶數則無中間數字問題可直接使用middle_index做區隔
if sum(num_string[:middle_index]) == sum(num_string[middle_index:]):
return True
return False